package controllers

import (
	"errors"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"github.com/myblogs/logic"
	"github.com/myblogs/models"
	"github.com/myblogs/pkg/snowflake"
	"go.uber.org/zap"
)

type TagController struct {
	tagLogic *logic.TagLogic
}

func NewTagController(tagLogic *logic.TagLogic) *TagController {
	return &TagController{
		tagLogic: tagLogic,
	}
}
func (t *TagController) CreateTagHandler(c *gin.Context) {
	var tag models.Tags
	if err := c.ShouldBindJSON(&tag); err != nil {
		errs, ok := err.(validator.ValidationErrors)
		if ok {
			zap.S().Error("标签参数错误", zap.Error(err))
			ResponseWithMsg(c, CodeInvalidParam, removeTopStruct(errs.Translate(trans)))
			return
		}
		Response(c, CodeInvalidParam)
		return
	}
	tag.TagID = snowflake.NewSnowflake(time.Now(), 1).GetID()
	if err := t.tagLogic.CreateTag(c, &tag); err != nil {
		if errors.Is(err, logic.ErrorTagExits) {
			zap.S().Error("标签已存在", zap.Error(err))
			ResponseWithMsg(c, CodeTagExits, "标签已存在")
			return
		}
		zap.S().Error("创建标签失败", zap.Error(err))
		Response(c, CodeTagError)
		return
	}
	Response(c, CodeSuccess)
}
func (t *TagController) GetAllTagsHandler(c *gin.Context) {
	tags, err := t.tagLogic.GetAllTags(c)
	if err != nil {
		zap.S().Error("获取标签失败", zap.Error(err))
		Response(c, CodeTagError)
		return
	}
	ResponseSuccess(c, CodeSuccess, tags)
}
